<?php 
class GoodsattrModel extends Model{
	public $table="goods_attr";
	
	
	public function addAttr($gid){
	    //添加属性
	    $attr= isset($_POST['attr']) ? $_POST['attr'] :array();
		
		foreach ($attr as $k => $v) {
			
				$data=array(
				   'gtvalue'=>$v,
				   'shop_typeattr_taid'=>$k,
				   'goods_gid'=>$gid
				);
				$this->add($data);
			
			
		}
//		p($_POST['spec']);die;
		//添加规格
		$spec= isset($_POST['spec']) ? $_POST['spec'] :array();
		foreach ($spec as $taid => $value) {
			foreach ($value['value'] as $k => $v) {
				
				$data=array(
				   'gtvalue'=>$v,
				   'shop_typeattr_taid'=>$taid,
				   'goods_gid'=>$gid,
				   'added'=>$value['added'][$k],
				);
//				p($data);
			
				$this->add($data);
			
				
			}
			
		}
		
		
		
		return true;
	}
	
	
	
	/**
	 * 通过商品的gid获得商品属性
	 */
	public function gidGetAttr($gids){
		//通过商品gid获得商品属性
		$attr = $this->where("goods_gid in(" . implode(',', $gids) . ")")->group('gtvalue')->all();
		//把同一taid的属性归结在一起
		$temp1 = array();
		foreach ($attr as $v) {
			$temp1[$v['shop_typeattr_taid']][] = $v;
		}
		//让数组有类型属性名称和所对应的值
		$temp2 = array();
		$model = M('shop_typeattr');
		foreach ($temp1 as $taid => $v) {
			$temp2[] = array(
				'name' => $model->where('taid=' . $taid)->getField('taname'),
				'value'=> $v
			);
		}
		return $temp2;
	}
	
	
	/**
	 * 通过筛选参数，筛选商品gid
	 */
	public function filterGids($param,$gids){
		$gid = array();
		foreach ($param as $gtid) {
			//如果不是选择“不限”
			if($gtid){
				$gid[] = M()->join('__goods_attr__ ga1 JOIN __goods_attr__ ga2 ON ga1.gtvalue=ga2.gtvalue')->where("ga1.gtid={$gtid}")->getField('ga2.goods_gid',true);
			}
		}
		//如果不是全部选择“不限”的时候，取交集，证明有选择其他，比如选择了M
		if($gid){
			//取交集，第一个和第二个取交集，上两个的结果再和最后一个取交集
			foreach ($gid as $key => $value) {
				if($key == 0){
					$temp = $value;
				}else{
					$temp = array_intersect($gid[$key], $temp);
				}
			}
			//筛选出来的数组再和分类所获得的gid取交集
			$gids = array_intersect($temp, $gids);
		}
		//如果全部是“不限”的时候，返出该分类下面的所有的gid
		return $gids;
		
	}
	
	
	
	
	
	
	
}




 ?>